package com.cyan.app.workflow.activity.Wap;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import com.cyan.app.workflow.AppContext;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.CommonBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;

import org.json.JSONObject;

/**
 * Created by DXW on 2016-08-09.
 */
public class WebView1Activity extends BaseActivity {
    public static final String TAG = "WebView1Activity";
    private TextView mTextViewCode;
    private String code="";
    private String type="";
    private WebView mWebView1;
    private String weburl = "";
    private ShowTipDialog showdialog = new ShowTipDialog();


    private ValueCallback<Uri> mUploadFile;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webpage1);
        initView();
        mWebView1 = (WebView) findViewById(R.id.web1);
        mWebView1.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setProgress(newProgress * 100);
            }

            @Override
            @SuppressLint("NewApi")
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
               // return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
                if (mUploadCallbackAboveL != null) {
                    mUploadCallbackAboveL.onReceiveValue(null);
                }
                mUploadCallbackAboveL = filePathCallback;
                //new PopupWindows(OADetailActivity.this, ll_main);
                return true;
            }
        });
        mWebView1.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                String dataString = AppUtils.getFromAssets(AppContext.getInstance(), "404.html");
                view.loadDataWithBaseURL("404.html", dataString, "text/html", "UTF-8", "");
            }
        });
        mWebView1.getSettings().setJavaScriptEnabled(true);
        mWebView1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWebView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView1.getSettings().setAllowFileAccess(true);
        mWebView1.getSettings().setLoadWithOverviewMode(true);



        mWebView1.getSettings().setDomStorageEnabled(true);
        mWebView1.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

        mWebView1.getSettings().setSupportZoom(true);
        mWebView1.getSettings().setBuiltInZoomControls(true);

        mWebView1.getSettings().setUseWideViewPort(true);
        mWebView1.getSettings().setLoadWithOverviewMode(true);

        if (android.os.Build.VERSION.SDK_INT > 10) {
            mWebView1.getSettings().setDisplayZoomControls(false);
        }
        type = getIntent().getStringExtra("Type");
        code = getIntent().getStringExtra("Code");
        if (type.isEmpty()||code.isEmpty()) return;
        mTextViewCode.setText(code);
        AsyncLoader task = new AsyncLoader();
        task.execute("001", type, code);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView1.canGoBack()) {
            mWebView1.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    public class AsyncLoader extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showdialog.showDialog(WebView1Activity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Type", params[1]);
                param.put("Code", params[2]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            CommonBean commonBean = new Gson().fromJson(s, CommonBean.class);
            if (commonBean.getCode() < 1) {
                AppUtils.showTip(WebView1Activity.this, commonBean.getMsg());
            } else {
                weburl = commonBean.getResult();
                if(type.equals("202")){
                    weburl = weburl +"?userid=" + AppData.getInstance().getUserId();
                }
                if(type.equals("401")){
                    weburl = weburl;
                }
                mWebView1.loadUrl(weburl);
            }
            showdialog.closeDialog();
        }
    }
    private void initView(){
        titleBar();
    }

    private void titleBar() {
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                //WebViewActivity.this.setResult(RESULT_OK);
                finish();
            }
        });

        mTextViewCode = (TextView)findViewById(R.id.top_title_info);
    }
}
